package cc.admin.modules.graduate.service.impl;

import cc.admin.common.sys.vo.LoginUser;
import cc.admin.modules.graduate.entity.*;
import cc.admin.modules.graduate.entity.DTO.DesignQuestionsListDto;
import cc.admin.modules.graduate.entity.VO.ExamPaperSmdVo;
import cc.admin.modules.graduate.entity.VO.ExamPaperVo;
import cc.admin.modules.graduate.mapper.*;
import cc.admin.modules.graduate.service.IChoiceErrorQuestionsService;
import cc.admin.modules.graduate.service.IExamPaperSmdService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import me.zhyd.oauth.utils.UuidUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 包含单选多选和应用的试卷
 * @Author: cc-admin
 * @Date: 2025-02-25
 * @Version: V1.0.0
 */
@Service
public class ExamPaperSmdServiceImpl extends ServiceImpl<ExamPaperSmdMapper, ExamPaperSmd> implements IExamPaperSmdService {

    @Autowired
    ChoiceQuestionsMapper choiceQuestionsMapper;

    @Autowired
    IChoiceErrorQuestionsService choiceErrorQuestionsService;

    @Autowired
    MultiChoiceQuestionsMapper multiChoiceQuestionsMapper;

    @Autowired
    DesignQuestionsListMapper designQuestionsListMapper;

    @Autowired
    DesignQuestionsMapper designQuestionsMapper;

    @Autowired
    ExamPaperSmdMapper examPaperSmdMapper;

    @Autowired
    ExamPaperAnswerSmdMapper examPaperAnswerSmdMapper;

    @Autowired
    ChoiceErrorQuestionsMapper choiceErrorQuestionsMapper;

    @Autowired
    DesignAnswerMapper designAnswerMapper;

    @Autowired
    DesignAnswerListMapper designAnswerListMapper;

    @Autowired
    private ChoiceErrorQuestionsMultiMapper choiceErrorQuestionsMultiMapper;
    @Autowired
    private ChoiceErrorQuestionsMultiServiceImpl choiceErrorQuestionsMultiServiceImpl;

    /*
     * percent 要分配的集合
     *
     * numberToAllocate   被分配的整数
     *
     * */
    public int[] allocatePercent(List<String> percent, Integer numberToAllocate) {


        double totalPercent = 0;
        double[] percentValues = new double[percent.size()];

        // 计算非空比例的总和
        for (int i = 0; i < percent.size(); i++) {
            String strPercent = percent.get(i);
            if (!strPercent.isEmpty()) {
                try {
                    percentValues[i] = Double.parseDouble(strPercent);
                    totalPercent += percentValues[i];
                } catch (NumberFormatException e) {
                    System.out.println("Invalid percentage at index " + i);
                }
            }
        }

        if (totalPercent == 0) {
            System.out.println("No valid percentages provided, cannot allocate.");
            return null;
        }

        int[] allocatedNumbers = new int[percent.size()];
        int remaining = numberToAllocate; // 记录剩余未分配的数量

        // 按比例分配整数（先按照比例分配）
        for (int i = 0; i < percent.size(); i++) {
            if (!percent.get(i).isEmpty()) {
                double proportion = percentValues[i] / totalPercent;
                int allocated = (int) (proportion * numberToAllocate);
                allocatedNumbers[i] = allocated;
                remaining -= allocated;
            } else {
                allocatedNumbers[i] = 0;
            }
        }

        // 将剩余数量分配给非空比例项（从第一个非空比例项开始循环分配）
        int index = 0;
        while (remaining > 0) {
            if (!percent.get(index).isEmpty()) {
                allocatedNumbers[index]++;
                remaining--;
            }
            index = (index + 1) % percent.size();
        }

        for (int i = 0; i < percent.size(); i++) {
            System.out.println("Allocated number for index " + i + ": " + allocatedNumbers[i]);
        }
        return allocatedNumbers;
    }

    @Override
    public void saveExam(ExamPaperSmd examPaperSmd) {
        Map<String, Percent> choicepercentObjectList = examPaperSmd.getChoicePercent();
        Map<String, Percent> designpercentObjectList = examPaperSmd.getDesignPercent();
        Map<String, Percent> multiChoicePercentObjectList = examPaperSmd.getMultiChoicePercent();


        HashMap<String, List<DesignQuestionsListDto>> designQuestionsMap = getDesignQuestionsMap(designpercentObjectList, examPaperSmd);
        // 获取每个科目的选择题
        HashMap<String, List<ChoiceQuestions>> choiceQuestionsMap = getChoiceQuestionsMap(choicepercentObjectList, examPaperSmd);
        // 获取多选
        HashMap<String, List<MultiChoiceQuestions>> multiChoiceQuestionsMap = new HashMap<>();
        if (multiChoicePercentObjectList != null) {
            multiChoiceQuestionsMap = getMultiChoiceQuestionsMap(multiChoicePercentObjectList, examPaperSmd);
        }

        ArrayList<String> choiceQuestionIds = new ArrayList<>();
        //根据每个科目的选择题获得id集合
        choiceQuestionsMap.forEach((tab, choiceQuestionsList) -> {
            choiceQuestionsList.forEach(choiceQuestions -> {
                String choiceQuestionsId = choiceQuestions.getId();
                choiceQuestionIds.add(choiceQuestionsId);
            });
        });
        ArrayList<String> designQuestionIds = new ArrayList<>();
        //根据每个科目的选择题获得id集合
        designQuestionsMap.forEach((tab, designQuestionsList) -> {
            designQuestionsList.forEach(designQuestions -> {
                String designQuestionsId = designQuestions.getId();
                designQuestionIds.add(designQuestionsId);
            });
        });

        ArrayList<String> multiChoiceQuestionIds = new ArrayList<>();
        //根据每个科目的多选题获得id集合
        multiChoiceQuestionsMap.forEach((tab, multiChoiceQuestions) -> {
            multiChoiceQuestions.forEach(multiChoiceQuestion -> {
                String multiChoiceQuestionsId = multiChoiceQuestion.getId();
                multiChoiceQuestionIds.add(multiChoiceQuestionsId);
            });
        });
        String choiceQuestionIdsString = String.join(",", choiceQuestionIds);
        String designQuestionIdsString = String.join(",", designQuestionIds);
        if (multiChoiceQuestionIds != null) {
            String multiChoiceQuestionIdsString = String.join(",", multiChoiceQuestionIds);
            examPaperSmd.setMultiChoiceIds(multiChoiceQuestionIdsString);
        }
        examPaperSmd.setChoiceIds(choiceQuestionIdsString);
        examPaperSmd.setDesignIds(designQuestionIdsString);
        examPaperSmdMapper.insert(examPaperSmd);
    }

    @Override
    public ExamPaperSmdVo getexampaper(String id) {

        String id1 = JSONObject.parseObject(id).getString("id");
        LambdaQueryWrapper<ExamPaperSmd> examPaperLambdaQueryWrapper = new LambdaQueryWrapper<>();
        examPaperLambdaQueryWrapper.eq(id != null, ExamPaperSmd::getId, id1);
        ExamPaperSmd examPaper = examPaperSmdMapper.selectOne(examPaperLambdaQueryWrapper);
        String[] designQuestionIds = null;
        if (examPaper.getDesignIds() != null) {
            designQuestionIds = examPaper.getDesignIds().split(",");
        }
        String[] choiceQuestionIds = null;
        if (examPaper.getChoiceIds() != null) {
            choiceQuestionIds = examPaper.getChoiceIds().split(",");
        }
        String[] multiChoiceQuestionIds = new String[0];
        if (examPaper.getMultiChoiceIds() != null && examPaper.getMultiChoiceIds() != "") {
            multiChoiceQuestionIds = examPaper.getMultiChoiceIds().split(",");
        }
        ExamPaperSmdVo examPaperVo = new ExamPaperSmdVo();
        BeanUtils.copyProperties(examPaper, examPaperVo);
        examPaperVo.setDesignIds(examPaper.getDesignIds());
        if (designQuestionIds.length != 0) {
            List<String> designQuestionIdsList = Arrays.stream(designQuestionIds).collect(Collectors.toList());
            List<DesignQuestionsListDto> DesignQuestionsList = designQuestionsListMapper.selectBatchIds(designQuestionIdsList);

            DesignQuestionsList.forEach(designQuestionsListDto -> {
                //放应用题的子数据
                String childIds = designQuestionsListDto.getChildIds();
                List<String> childIdsList = Arrays.stream(childIds.split(",")).collect(Collectors.toList());
                List<DesignQuestions> designQuestions = designQuestionsMapper.selectBatchIds(childIdsList);
                designQuestionsListDto.setQuestionList(designQuestions);
            });

            examPaperVo.setDesignQuestionsListDtoList(DesignQuestionsList);
        }

        examPaperVo.setChoiceIds(examPaper.getChoiceIds());
        if (choiceQuestionIds.length != 0) {
            List<String> choiceQuestionIdsList = Arrays.stream(choiceQuestionIds).collect(Collectors.toList());
            List<ChoiceQuestions> choiceQuestionsList = choiceQuestionsMapper.selectBatchIds(choiceQuestionIdsList);
            examPaperVo.setChoiceQuestionsList(choiceQuestionsList);
        }
        examPaperVo.setMultiChoiceIds(examPaper.getMultiChoiceIds());
        if (multiChoiceQuestionIds.length != 0) {
            List<String> multiChoiceQuestionIdsList = Arrays.stream(multiChoiceQuestionIds).collect(Collectors.toList());
            List<MultiChoiceQuestions> multiChoiceQuestionsList = multiChoiceQuestionsMapper.selectBatchIds(multiChoiceQuestionIdsList);
            java.lang.reflect.Type type = new TypeToken<List<option>>() {
            }.getType();
            java.lang.reflect.Type stringType = new TypeToken<List<String>>() {
            }.getType();
            Gson gson = new Gson();
            multiChoiceQuestionsList.forEach(multiChoiceQuestions -> {
                multiChoiceQuestions.setOption(gson.fromJson(multiChoiceQuestions.getOptionJson(), type));
                multiChoiceQuestions.setAnswer(gson.fromJson(multiChoiceQuestions.getAnswerJson(), stringType));
            });
            examPaperVo.setMultiChoiceQuestionsList(multiChoiceQuestionsList);
        }
        return examPaperVo;
    }

    @Override
    @Transactional
    public void saveExamAnswer(ExamPaperAnswerSmd examPaperAnswer) {
        String id = examPaperAnswer.getId();
        ExamPaperSmd examPaper = new ExamPaperSmd();
        LambdaUpdateWrapper<ExamPaperSmd> examPaperLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        examPaperLambdaUpdateWrapper.eq(ExamPaperSmd::getId, id);
        examPaperLambdaUpdateWrapper.set(ExamPaperSmd::getType, "已完成");
        examPaperSmdMapper.update(examPaper, examPaperLambdaUpdateWrapper);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();


        List<String> choiceAnswer = examPaperAnswer.getChoiceAnswer();
        if (choiceAnswer != null) {
            List<ChoiceQuestions> choiceQuestionsList = examPaperAnswer.getChoiceQuestionsList();
            //存入选择题错题
            for (int i = 0; i < choiceQuestionsList.size(); i++) {
                if (!choiceQuestionsList.get(i).getAnswer().equals(choiceAnswer.get(i))) {
                    ChoiceErrorQuestions choiceErrorQuestions = new ChoiceErrorQuestions();
                    ChoiceQuestions choiceQuestions = choiceQuestionsList.get(i);
                    BeanUtils.copyProperties(choiceQuestions, choiceErrorQuestions);
                    choiceErrorQuestions.setQuestionId(choiceErrorQuestions.getId());
                    String uuid = UuidUtils.getUUID();
                    choiceErrorQuestions.setId(uuid);
                    choiceErrorQuestions.setRealAnswer(choiceErrorQuestions.getAnswer());
                    choiceErrorQuestions.setAnswer(choiceAnswer.get(i));
                    choiceErrorQuestions.setUserId(user.getUsername());
                    String choiceErrId = UuidUtils.getUUID();
                    choiceErrorQuestions.setId(choiceErrId);
                    choiceErrorQuestionsMapper.insert(choiceErrorQuestions);
                }
            }
        }
        //存放选择题答案
        Gson gson = new Gson();
        String choiceAnswerString = gson.toJson(choiceAnswer);
        examPaperAnswer.setChoiceAnswerJson(choiceAnswerString);

        //存放多选题答案和对错
        List<List<String>> multiChoiceAnswer = examPaperAnswer.getMultiChoiceAnswer();
        List<MultiChoiceQuestions> multiChoiceQuestionList = examPaperAnswer.getMultiChoiceQuestionsList();
        ArrayList<String> multiChoiceResult = new ArrayList<>();
        for (int i = 0; i < multiChoiceQuestionList.size(); i++) {
            List<String> realAnswerList = multiChoiceQuestionList.get(i).getAnswer();
            List<String> answerList = multiChoiceAnswer.get(i);
            String b = areListsEqual(realAnswerList, answerList) ? "1" : "0";
            multiChoiceResult.add(b);
            if (b.equals("0")) {
                //录入多选题错题
                ChoiceErrorQuestionsMulti multiChoiceErrorQuestions = new ChoiceErrorQuestionsMulti();
                MultiChoiceQuestions choiceQuestions = multiChoiceQuestionList.get(i);
                BeanUtils.copyProperties(choiceQuestions, multiChoiceErrorQuestions);
                multiChoiceErrorQuestions.setQuestionId(choiceQuestions.getId());
                multiChoiceErrorQuestions.setId(UuidUtils.getUUID());
                multiChoiceErrorQuestions.setAnswerJsonReal(choiceQuestions.getAnswerJson());
                multiChoiceErrorQuestions.setAnswerJson(gson.toJson(answerList));
                multiChoiceErrorQuestions.setUserId(user.getUsername());
                choiceErrorQuestionsMultiMapper.insert(multiChoiceErrorQuestions);
            }
        }
        String multiChoiceAnswerJson = gson.toJson(multiChoiceAnswer);
        String multiChoiceResultJson = gson.toJson(multiChoiceResult);
        examPaperAnswer.setMultiChoiceAnswerJson(multiChoiceAnswerJson);
        examPaperAnswer.setMultiChoiceResultString(multiChoiceResultJson);


        //存放应用题
        ArrayList<String> designAnserIdList = new ArrayList<>();
        List<DesignAnswerList> designAnswerList = examPaperAnswer.getDesignAnswer();
        designAnswerList.forEach(designQuestionsListDto -> {
            String parentId = UuidUtils.getUUID();
            //将应用题的所有小题保存进做题表中
            designQuestionsListDto.getQuestionList().forEach(designQuestions -> {
                DesignAnswer designAnswer = new DesignAnswer();
                BeanUtils.copyProperties(designQuestions, designAnswer);
                designAnswer.setUserId(user.getId());
                designAnswer.setUserName(user.getRealname());
                String uuid = UuidUtils.getUUID();
                designAnswer.setQuestionId(designAnswer.getId());
                designAnswer.setParentId(parentId);
                designAnswer.setId(uuid);
                designAnswerMapper.insert(designAnswer);
            });
            DesignAnswerList designAnswerList1 = new DesignAnswerList();
            BeanUtils.copyProperties(designQuestionsListDto, designAnswerList1);
            designAnswerList1.setUserName(user.getRealname());
            designAnswerList1.setQuestionId(designAnswerList1.getId());
            designAnswerList1.setId(parentId);
            designAnserIdList.add(parentId);
            //将应用题的所有大题保存到主表中
            designAnswerListMapper.insert(designAnswerList1);


        });
        String designAnserIdListString = StringUtils.join(designAnserIdList, ",");
        examPaperAnswer.setDesignAnswerIds(designAnserIdListString);
        String uuid = UuidUtils.getUUID();
        examPaperAnswer.setExamPaperId(examPaperAnswer.getId());
        examPaperAnswer.setId(uuid);
        examPaperAnswer.setType("已审批");
        examPaperAnswerSmdMapper.insert(examPaperAnswer);
    }

    public HashMap<String, List<DesignQuestionsListDto>> getDesignQuestionsMap(Map<String, Percent> percentObjectMap, ExamPaperSmd examPaper) {
        HashMap<String, List<DesignQuestionsListDto>> allQuestionMap = new HashMap<>();
        String needError = examPaper.getNeedError();
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ArrayList<String> questionIds = new ArrayList<>();
        Set<String> tabSet = new HashSet<String>();
//        for (int i = 0; i < percentObjectList.size(); i++) {
//
//        }
        final int[] i = {0};
        percentObjectMap.forEach((tab, percent) -> {
            //该科目所有选择题的集合
            List<DesignQuestionsListDto> allQuestionList = new ArrayList<>();
            List<String> percentArr1 = percent.getPercentArr();
            tabSet.add(tab);
            //每科题目总数
            Integer quastionQuantity = examPaper.getDesignQuantity().get(i[0]);
            // 应用题总数设置
            int[] percentArr = allocatePercent(percentArr1, quastionQuantity);
            //便利每个科目集合
            if (percentArr != null) {
                for (int j = 0; j < percentArr.length; j++) {
                    //每个题目所占的题数
                    Integer ItemPercent = percentArr[j];
                    List<DesignQuestionsListDto> DesignQuestionsList = null;
                    if (needError == null || needError.equals("2")) {
                        DesignQuestionsList = designQuestionsListMapper.questionsList(String.valueOf(j + 1), ItemPercent, tab);
                    } else {
                        // 查询当前用户错误选择题的id
                        ArrayList<String> errorIds = new ArrayList<>();
                        LambdaQueryWrapper<DesignAnswerList> errorQueryWrapper1 = new LambdaQueryWrapper<>();
                        errorQueryWrapper1.eq(DesignAnswerList::getUserId, user.getUsername());
                        errorQueryWrapper1.groupBy(DesignAnswerList::getQuestionId);
                        errorQueryWrapper1.select(DesignAnswerList::getQuestionId);
                        List<Map<String, Object>> maps = designAnswerListMapper.selectMaps(errorQueryWrapper1);
                        maps.forEach(errorQuestions -> {
                            if (errorQuestions != null) {
                                errorIds.add(errorQuestions.get("question_id").toString());
                            }
                        });
                        // 查询选择题
                        LambdaQueryWrapper<DesignQuestionsListDto> queryWrapper = new LambdaQueryWrapper<>();
                        // 查询题目类型
                        if (String.valueOf(j + 1) != null && !String.valueOf(j + 1).isEmpty()) {
                            queryWrapper.like(DesignQuestionsListDto::getCategoryIds, String.valueOf(j + 1));
                        }

                        // 按 tab 筛选
                        if (tab != null && !tab.isEmpty()) {
                            queryWrapper.eq(DesignQuestionsListDto::getMajorId, tab);
                        }
                        if (errorIds.size() > 0) {
                            queryWrapper.in(DesignQuestionsListDto::getId, errorIds);
                        }
                        // 查询数据条数
                        if (ItemPercent != null) {
                            queryWrapper.last("ORDER BY RAND() LIMIT " + ItemPercent);
                        }
                        DesignQuestionsList = designQuestionsListMapper.selectList(queryWrapper);
                    }
                    allQuestionList.addAll(DesignQuestionsList);
                    allQuestionList.forEach(designQuestions -> {
                        questionIds.add(designQuestions.getId());
                    });
                }
            }
            allQuestionMap.put(tab, allQuestionList);
            i[0]++;
        });
        return allQuestionMap;
    }

    public HashMap<String, List<ChoiceQuestions>> getChoiceQuestionsMap(Map<String, Percent> percentObjectMap, ExamPaperSmd examPaper) {
        HashMap<String, List<ChoiceQuestions>> allQuestionMap = new HashMap<>();
        String needError = examPaper.getNeedError();
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ArrayList<String> questionIds = new ArrayList<>();
        Set<String> tabSet = new HashSet<String>();
//        for (int i = 0; i < percentObjectList.size(); i++) {
//
//        }
        final int[] i = {0};
        percentObjectMap.forEach((tab, percent) -> {
            //该科目所有选择题的集合
            List<ChoiceQuestions> allQuestionList = new ArrayList<>();
            List<String> percentArr1 = percent.getPercentArr();
            tabSet.add(tab);
            //每科题目总数
            Integer quastionQuantity = examPaper.getChoiceQuantity().get(i[0]);
            int[] percentArr = allocatePercent(percentArr1, quastionQuantity);
            //便利每个科目集合
            if (percentArr != null) {
                for (int j = 0; j < percentArr.length; j++) {
                    //每个题目所占的题数
                    Integer ItemPercent = percentArr[j];
                    List<ChoiceQuestions> ChoiceQuestionsList = null;
                    if (needError == null || needError.equals("2")) {
                        ChoiceQuestionsList = choiceQuestionsMapper.questionsList(String.valueOf(j + 1), ItemPercent, tab);
                    } else {
                        // 查询当前用户错误选择题的id
                        ArrayList<String> errorIds = new ArrayList<>();
                        LambdaQueryWrapper<ChoiceErrorQuestions> errorQueryWrapper1 = new LambdaQueryWrapper<>();
                        errorQueryWrapper1.eq(ChoiceErrorQuestions::getUserId, user.getUsername());
                        errorQueryWrapper1.groupBy(ChoiceErrorQuestions::getQuestionId);
                        errorQueryWrapper1.select(ChoiceErrorQuestions::getQuestionId);
                        List<Map<String, Object>> maps = choiceErrorQuestionsService.listMaps(errorQueryWrapper1);
                        maps.forEach(errorQuestions -> {
                            if (errorQuestions != null) {
                                errorIds.add(errorQuestions.get("question_id").toString());
                            }
                        });
                        // 查询选择题
                        LambdaQueryWrapper<ChoiceQuestions> queryWrapper = new LambdaQueryWrapper<>();
                        // 查询题目类型
                        if (String.valueOf(j + 1) != null && !String.valueOf(j + 1).isEmpty()) {
                            queryWrapper.like(ChoiceQuestions::getCategoryIds, String.valueOf(j + 1));
                        }

                        // 按 tab 筛选
                        if (tab != null && !tab.isEmpty()) {
                            queryWrapper.eq(ChoiceQuestions::getMajorId, tab);
                        }
                        if (errorIds.size() > 0) {
                            queryWrapper.in(ChoiceQuestions::getId, errorIds);
                        }
                        // 查询数据条数
                        if (ItemPercent != null) {
                            queryWrapper.last("ORDER BY RAND() LIMIT " + ItemPercent);
                        }
                        ChoiceQuestionsList = choiceQuestionsMapper.selectList(queryWrapper);
                    }
                    allQuestionList.addAll(ChoiceQuestionsList);
                    allQuestionList.forEach(ChoiceQuestions -> {
                        questionIds.add(ChoiceQuestions.getId());
                    });
                }
            }
            allQuestionMap.put(tab, allQuestionList);
            i[0]++;
        });
        return allQuestionMap;
    }

    public HashMap<String, List<MultiChoiceQuestions>> getMultiChoiceQuestionsMap(Map<String, Percent> percentObjectMap, ExamPaperSmd examPaper) {
        HashMap<String, List<MultiChoiceQuestions>> allQuestionMap = new HashMap<>();
        String needError = examPaper.getNeedError();
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ArrayList<String> questionIds = new ArrayList<>();
        Set<String> tabSet = new HashSet<String>();
//        for (int i = 0; i < percentObjectList.size(); i++) {
//
//        }
        final int[] i = {0};
        percentObjectMap.forEach((tab, percent) -> {
            //该科目所有选择题的集合
            List<MultiChoiceQuestions> allQuestionList = new ArrayList<>();
            List<String> percentArr1 = percent.getPercentArr();
            tabSet.add(tab);
            //每科题目总数
            Integer quastionQuantity = examPaper.getMultiChoiceQuantity().get(i[0]);
            int[] percentArr = allocatePercent(percentArr1, quastionQuantity);
            //便利每个科目集合
            if (percentArr != null) {
                for (int j = 0; j < percentArr.length; j++) {
                    //每个题目所占的题数
                    Integer ItemPercent = percentArr[j];
                    List<MultiChoiceQuestions> multiChoiceQuestionsList = null;
                    if (needError == null || needError.equals("2")) {
                        multiChoiceQuestionsList = multiChoiceQuestionsMapper.questionsList(String.valueOf(j + 1), ItemPercent, tab);
                    }else {
                        // 查询当前用户错误选择题的id
                        ArrayList<String> errorIds = new ArrayList<>();
                        LambdaQueryWrapper<ChoiceErrorQuestionsMulti> errorQueryWrapper1 = new LambdaQueryWrapper<>();
                        errorQueryWrapper1.eq(ChoiceErrorQuestionsMulti::getUserId, user.getUsername());
                        errorQueryWrapper1.groupBy(ChoiceErrorQuestionsMulti::getQuestionId);
                        errorQueryWrapper1.select(ChoiceErrorQuestionsMulti::getQuestionId);
                        List<Map<String, Object>> maps = choiceErrorQuestionsMultiServiceImpl.listMaps(errorQueryWrapper1);
                        maps.forEach(errorQuestions -> {
                            if (errorQuestions != null) {
                                errorIds.add(errorQuestions.get("question_id").toString());
                            }
                        });
                        // 查询选择题
                        LambdaQueryWrapper<MultiChoiceQuestions> queryWrapper = new LambdaQueryWrapper<>();
                        // 查询题目类型
                        if (String.valueOf(j + 1) != null && !String.valueOf(j + 1).isEmpty()) {
                            queryWrapper.like(MultiChoiceQuestions::getCategoryIds, String.valueOf(j + 1));
                        }

                        // 按 tab 筛选
                        if (tab != null && !tab.isEmpty()) {
                            queryWrapper.eq(MultiChoiceQuestions::getMajorId, tab);
                        }
                        if (errorIds.size() > 0) {
                            queryWrapper.in(MultiChoiceQuestions::getId, errorIds);
                        }
                        // 查询数据条数
                        if (ItemPercent != null) {
                            queryWrapper.last("ORDER BY RAND() LIMIT " + ItemPercent);
                        }
                        multiChoiceQuestionsList = multiChoiceQuestionsMapper.selectList(queryWrapper);
                    }
                    allQuestionList.addAll(multiChoiceQuestionsList);
                    allQuestionList.forEach(ChoiceQuestions -> {
                        questionIds.add(ChoiceQuestions.getId());
                    });
                }
            }
            allQuestionMap.put(tab, allQuestionList);
            i[0]++;
        });
        return allQuestionMap;
    }

    public static boolean areListsEqual(List<String> list1, List<String> list2) {
        // 若两个列表长度不同，内容肯定不相等
        if (list1.size() != list2.size()) {
            return false;
        }

        // 用于统计 list1 中每个元素出现的频率
        Map<String, Integer> frequencyMap1 = new HashMap<>();
        for (String element : list1) {
            frequencyMap1.put(element, frequencyMap1.getOrDefault(element, 0) + 1);
        }

        // 用于统计 list2 中每个元素出现的频率
        Map<String, Integer> frequencyMap2 = new HashMap<>();
        for (String element : list2) {
            frequencyMap2.put(element, frequencyMap2.getOrDefault(element, 0) + 1);
        }

        // 比较两个频率统计 Map 是否相同
        return frequencyMap1.equals(frequencyMap2);
    }
}
